package cn.layou.thread;

import sun.misc.Contended;

import java.util.concurrent.CountDownLatch;

/**
 * 演示缓存行填充对多线程程序的影响-缓存行默认大小为64个字节
 *
 * @author layou
 * @date 2021-04-16
 **/
public class T03_ThreadCacheLinePadding {
    public static long count = 10_0000_0000L;

    private static class T{
        //通过前后填充属性，使得两个对象不在同一个缓存行上，避免产生缓存一致性行为，提高系统效率
        //private long p1, p2, p3, p4, p5, p6, p7;
        //@Contended //也可以通过这个注解实现,并增加vm参数-XX:-RestrictContended，但只再jdk1.8生效
        public long x = 0L;//8个字节
        //private long p9, p10, p11, p12, p13, p14, p15;
    }

    public static T[] arr = new T[2];
    static {
        arr[0] = new T();
        arr[1] = new T();
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(2);


        Thread t1 = new Thread(() -> {
            for(long i= 0; i<count; i++) {
                arr[0].x = i;
            }
            latch.countDown();
        });

        Thread t2 = new Thread(() -> {
            for(long i= 0; i<count; i++) {
                arr[1].x = i;
            }
            latch.countDown();
        });

        long start = System.nanoTime();
        t1.start();
        t2.start();
        latch.await();
        long end = System.nanoTime();
        System.out.println("耗时:" + (end - start) / 100_0000L);


    }
}


